package com.ref.entity;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author wzm
 * @create 2023-02-14 10:08
 */
//测试反射获取成员变量
public class ReflectTest4 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
     //获取空参构造方法并创建对象
        //获取字节码文件对象
        Class clazz = Class.forName("com.ref.entity.Student");
        
        //1.获取所有public的成员变量对象
        Field[] fields1 = clazz.getFields();
        for(Field field : fields1){
            System.out.println("field = " + field);
        }

        System.out.println("------------------------------------");
        
        //2.获取所有的成员变量对象（public+private）
        Field[] fields2 = clazz.getDeclaredFields();
        for(Field field : fields2){
            System.out.println("field = " + field);
        }

        System.out.println("------------------------------------");
        
        //3.获取单个成员变量(public)
        Field id = clazz.getField("id");
       // Field aaa = clazz.getField("aaa"); 如果属性不存在 会报异常
        System.out.println("id = " + id);
       // System.out.println("aaa = " + aaa);

        System.out.println("------------------------------------");
        //获取单个成员变量 （带private）
        Field name = clazz.getDeclaredField("name");
        System.out.println("name = " + name);


    }
}
